package com.gitee.somenvm.ninerpgitem.core.template

import com.gitee.somenvm.ninerpgitem.api.event.plugin.NineRpgItemReloadEvent
import com.gitee.somenvm.ninerpgitem.core.Loader
import com.gitee.somenvm.ninerpgitem.util.info
import org.bukkit.command.CommandSender
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.event.SubscribeEvent
import taboolib.common.platform.function.console
import taboolib.common.platform.function.getDataFolder
import taboolib.common.platform.function.getJarFile
import taboolib.common.platform.function.releaseResourceFile
import taboolib.module.configuration.Configuration
import taboolib.module.configuration.util.map
import java.io.File
import java.util.jar.JarFile

/**
 * BY NineRpgItem
 * 模版载入
 *
 * @author  SomeNvM
 * @date  2023/6/13 00:14
 */
object TemplateLoader : Loader {
    /**
     * 已载入模版列表
     */
    val templates = hashMapOf<String, List<String>>()

    @Awake(LifeCycle.ENABLE)
    override fun load() {
        val file = File(getDataFolder(), "Template")

        if (!file.exists()) {
            JarFile(getJarFile()).entries().iterator().forEachRemaining {
                if (it.name.startsWith("Template/") && it.name.endsWith(".yml")) {
                    releaseResourceFile(it.name)
                }
            }
            console()
                .cast<CommandSender>()
                .info("生成示例模版文件, 请修改后使用 /nri reload template 重新载入.")
            load()
            return
        }

        templates.clear()
        loadTemplate(file)

        console()
            .cast<CommandSender>()
            .info(if (templates.size > 0) "共加载 ${templates.size} 个模版" else "无模版加载")
    }

    private fun loadTemplate(file: File) {
        when {
            file.isDirectory -> file.listFiles()?.forEach { loadTemplate(it) }
            file.extension.equals("yml", true) -> {

                Configuration.loadFromFile(file).map { k, v ->
                    when (v) {
                        is String -> templates[k] = listOf(v)
                        is List<*> -> templates[k] = v.map { it.toString() }
                        else -> {
                            templates[k] = listOf(v.toString())
                            console().cast<CommandSender>().info("模版 $k 配置错误.")
                        }
                    }
                }
            }
        }
    }

    @SubscribeEvent
    fun reload(e: NineRpgItemReloadEvent.Template) {
        console().cast<CommandSender>().info("重载模版.")
        load()
    }
}